
// 单例模式 在全局只有一个类的实例

// 业务 缓存 分离
class HistoryKeyword {
    static MAX_ITEM_COUNT = 20
    static KEY = "keywords"

    keywords = []

    constructor() {
        // 单例模式
        if (typeof HistoryKeyword.instance === 'object') {
            return this
        }
        this.keywords = this._getLocalKeywords()
        HistoryKeyword.instance = this
        return this
    }

    // 缓存中写入数据
    // 去重
    save(keyWord) {
        const itmes = this.keywords.filter(k => {
            return k === keyWord
        })
        if (itmes.length !== 0) {
            return
        }
        // [七秀、藏剑、纯阳] 3
        // 万花

        // 队列
        if (this.keywords.length >= HistoryKeyword.MAX_ITEM_COUNT) {
            this.keywords.pop()
        }
        this.keywords.unshift(keyWord)
        this._refreshLocal()
    }
    get() {
        return this.keywords
    }

    clear() {
        this.keywords = []
        this._refreshLocal()
    }

    _refreshLocal() {
        wx.setStorageSync(HistoryKeyword.KEY, this.keywords);
    }

    _getLocalKeywords() {
        const keywords = wx.getStorageSync(HistoryKeyword.KEY)
        if (!keywords) {
            wx.setStorageSync(HistoryKeyword.KEY, []);
            return []
        }
        return keywords
    }
}

export {
    HistoryKeyword
}